#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.

"""WebRTC Demo

This module demonstrates the WebRTC API by implementing a simple video chat app.
"""

import cgi
import logging
import os
import random
import re
import json
import jinja2
import webapp2
import threading
from google.appengine.api import channel
from google.appengine.ext import ndb

jinja_environment = jinja2.Environment(
		loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
		extensions=['jinja2.ext.autoescape'],
		autoescape=True)

def msg_key(msg_name='default_msg'):
	return ndb.Key('DefaultMsg', msg_name)

class MessModel(ndb.Model):
	author = ndb.UserProperty()
	fbId = ndb.StringProperty(indexed=False)
	content = ndb.StringProperty(indexed=False)
	latlong = ndb.GeoPtProperty()
	ip_addr = ndb.StringProperty(indexed=False)
	write_time = ndb.DateTimeProperty(auto_now_add=True)

# Lock for syncing DB operation in concurrent requests handling.
# TODO(brave): keeping working on improving performance with thread syncing.
# One possible method for near future is to reduce the message caching.

class MainPage(webapp2.RequestHandler):
	def get(self): 
		city = self.request.headers.get('X-AppEngine-City')
		latlong = self.request.headers.get('X-AppEngine-CityLatLong')
		msgs_query = MessModel.query(ancestor=msg_key()).order(-MessModel.write_time)
		msgs = msgs_query.fetch(20)
		target_page = 'index.html'
		template = jinja_environment.get_template(target_page)
		self.response.write(template.render(
			msgs = msgs,
			city = city,
			latlong = latlong,
			models = MessModel.query(),
			))
	def post(self):
		mode = self.request.get('mode')
		if mode == "postMsg":
			self.redirect('/test1')
			fbId = self.request.get('fbId')
			content = self.request.get('content')
			userLong = self.request.get('userLong')
			userLat = self.request.get('userLat')
			ip = self.request.remote_addr
			if userLong:
				msg = MessModel(parent=msg_key())
				msg.fbId = fbId
				msg.latlong = ndb.GeoPt(userLat, userLong)
				msg.content = content
				msg.ip_addr = ip;
				msg.put()
		elif mode == "centerChanged":
			self.redirect('/test2')
		else:
			self.redirect('/')

class Test1(webapp2.RequestHandler):
	def get(self):
		self.response.headers['Content-Type'] = 'text/plain'
		self.response.write('Hello, Test1')
class Test2(webapp2.RequestHandler):
	def get(self):
		self.response.headers['Content-Type'] = 'text/plain'
		self.response.write('Hello, Test2')

app = webapp2.WSGIApplication([
	('/', MainPage),
	('/test1', Test1),
	('/test2', Test2),
	], debug=True)
